﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.UI;
using RoketSolutions.SP2010.Infrostructure.Localization;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;

namespace RoketSolutions.SP2010.Infrostructure.UI.Controls
{

    public class LocalizableUserControl : UserControlBase, ILocalizableControl
    {
        const string EventResolveConfig = "ResolveConfig";
        public event Func<ResourceConfig> ResolveConfig
        {
            add { Events.AddHandler(EventResolveConfig, value); }
            remove { Events.RemoveHandler(EventResolveConfig, value); }
        }

        #region / Properties /

        ResourceConfig _config;
        protected ResourceConfig ResourceConfig
        {
            get { return _config ?? (_config = OnResolveConfig()); }
            set { _config = value; }
        }

        #endregion

        #region / Methods /

        public virtual void SetupConfig(ResourceConfig config)
        {
            ResourceConfig = config;
        }

        protected string GetLocalizedString<TSource>(Expression<Func<TSource, object>> propertyKey)
        {
            if (ResourceConfig == null)
                throw new InvalidOperationException("ResourceConfig is not specified.");

            return Resources.For<TSource>(ResourceConfig).Get(propertyKey);
        }

        private ResourceConfig OnResolveConfig()
        {
            var handler = Events[EventResolveConfig] as Func<ResourceConfig>;
            if (handler != null)
            {
                return handler();
            }
            return null;
        }

        #endregion

    }
}